const db = wx.cloud.database();
const user = db.collection('user')
const app = getApp()
Page({
  data: {
    show: false,
    actions: [],
    sexCheck: true,
    forSex: "男",
    // fileList: [],
  },
  BackUser() {
    wx.navigateBack({
      detail: 4
    })
  },
  onClose() {
    this.setData({ show: false });
  },
  onUpdate() {
    var that = this;
    wx.cloud.callFunction({
      name: "login"
    }).then(res => {
      //console.log(res.result.openid)
      user.where({
        _openid: res.result.openid
      }).update({
        data: {
          wxName: this.data.userName,
          sex: this.data.forSex,
          hobby: this.data.hobby,
          about: this.data.about,

        },
        success() {
          wx.showToast({
            title: '下次登录生效',
            icon: 'success'
          })
          that.onLoad()
        }
      })
    })
  },
  amend() {
    this.setData({
      show: true,
    })
  },
  /**
   * 文件上传
   */
  afterRead(event) {
    const { file } = event.detail;
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    wx.uploadFile({
      url: 'https://example.weixin.qq.com/upload', // 仅为示例，非真实的接口地址
      filePath: file.url,
      name: 'file',
      formData: { user: 'test' },
      success(res) {
        // 上传完成需要更新 fileList
        const { fileList = [] } = this.data;
        fileList.push({ ...file, url: res.data });
        this.setData({ fileList });
      },
    });
  },

  /**
   * 性别选择
   */
  sexChange(e) {
    this.setData({
      sexCheck: e.detail,
      forSex: e.detail ? "男" : "女"
    })

  },

  onLoad: function () {
    var that = this;
    if (app.getGlobalUserInfo().wxName != undefined) {
      wx.cloud.callFunction({
        name: "login"
      }).then(res => {
        //console.log(res.result.openid)
        user.where({
          _openid: res.result.openid
        }).get().then(res => {
          that.setData({
            profile: res.data[0].avatarUrl,
            userName: res.data[0].wxName,
            sex: res.data[0].sex,
            hobby: res.data[0].hobby,
            about: res.data[0].about,
            createTime: res.data[0].createTime
          })
        })
      })
    } else {
      wx.showToast({
        icon: "error",
        title: '未登录',
      })
    }
  },
})